package com.bp.hearthealth.pulse.lnapps.ads.admob.open_ad

import android.app.Activity
import android.content.Context
import com.anythink.interstitial.api.ATInterstitial
import com.bp.hearthealth.pulse.lnapps.BpApplication
import com.bp.hearthealth.pulse.lnapps.ads.timer.TimerObserver
import com.bp.hearthealth.pulse.lnapps.ads.model.AdsCount
import com.bp.hearthealth.pulse.lnapps.ads.model.AdsSwitch
import com.bp.hearthealth.pulse.lnapps.appsflyer.AppsFlyerUtils
import com.bp.hearthealth.pulse.lnapps.bp_extension.LogUtil
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_language_gender.bp_splash.BpSplashActivity
import com.bp.hearthealth.pulse.lnapps.bp_utils.Constants
import com.bp.hearthealth.pulse.lnapps.bp_utils.DateUtils
import com.google.android.gms.ads.AdError
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.FullScreenContentCallback
import com.google.android.gms.ads.LoadAdError
import com.google.android.gms.ads.appopen.AppOpenAd
import java.util.Date

class AdMobOpenAdManager : TimerObserver {

    private var adListener: OnShowAdCompleteListener? = null
    var appOpenAd: AppOpenAd? = null
    private var isLoadingAd = false
    var isShowingAd = false
    private var numberRetries = 0

    /**跟踪应用打开广告的加载时间，以确保您不会展示过期的广告。*/
    private var loadTime: Long = 0

    /**
     * Load an ad.
     *
     * @param context the context of the activity that loads the ad
     */
    fun loadAd(context: Context) {
        numberRetries = 0
        // Do not load ad if there is an unused ad or one is already loading.
        if (isLoadingAd || isAdAvailable(loadTime)) {
            return
        }
        isLoadingAd = true
        val request = AdRequest.Builder().build()
        AppOpenAd.load(context,
            Constants.App_Open,
            request,
            object : AppOpenAd.AppOpenAdLoadCallback() {
                override fun onAdLoaded(ad: AppOpenAd) {
                    appOpenAd = ad
                    isLoadingAd = false
                    loadTime = Date().time
                    LogUtil.i("开屏广告 onAdLoaded.")
                }

                override fun onAdFailedToLoad(loadAdError: LoadAdError) {
                    LogUtil.i("开屏广告 onAdFailedToLoad: " + loadAdError.message)
                    adListener?.onAdFailedToLoad()
                    if (numberRetries < 3) {
                        loadAd(context)
                    }
                    numberRetries++
                    isLoadingAd = false
                }
            })
    }


    /** 检查广告是否存在并且可以展示. */
    private fun isAdAvailable(loadTime: Long): Boolean {
        return appOpenAd != null && DateUtils.wasLoadTimeLessThanNHoursAgo(1, loadTime)
    }

    /**
     * 如果广告尚未展示，请展示该广告。
     *
     * @param activity 显示应用打开广告的 Activity
     */
    fun showAdIfAvailable(activity: Activity) {
        numberRetries = 0
        showAdIfAvailable(activity, object : OnShowAdCompleteListener {
            override fun onShowAdComplete() {
                if (activity is BpSplashActivity) {
                    LogUtil.i("OpenAdManager 进度结束")
                    activity.progressBarUpdater.simulateAnimationEnd()
                }
                LogUtil.i("OpenAdManager onShowAdComplete()")
                // Empty because the user will go back to the activity that shows the ad.
            }

            override fun onAdShowedFullScreenContent() {
                if (activity is BpSplashActivity) {
                    LogUtil.i("OpenAdManager 取消进度条")
                    activity.progressBarUpdater.cancel()
                }
                LogUtil.i("OpenAdManager onAdShowedFullScreenContent()")
                //前后台切换_开屏广告展示 ad_open_switch_show
                AppsFlyerUtils.trackEvent("ad_open_switch_show")
                ATInterstitial.entryAdScenario(Constants.TOP_ON_OPEN_ID,"f66471e7b77b00")
                LogUtil.iTopOn("TopOn 配置的场景ID为: 【前后台切换后_开屏广告】")
            }

            override fun onAdFailedToLoad() {

            }

            override fun onAdFailedToShowFullScreenContent() {

            }
        })
    }

    fun showAdIfAvailable(
        activity: Activity, onShowAdCompleteListener: OnShowAdCompleteListener,
    ) {
        this.adListener = onShowAdCompleteListener
        if (!AdsSwitch.getBoolean(AdsSwitch.adOpenControl)) {
            LogUtil.i("开屏广告 AdSwitch.getBoolean：${AdsSwitch.getBoolean(AdsSwitch.adOpenControl)}")
            onShowAdCompleteListener.onShowAdComplete()
            return
        }
        if (isShowingAd) {
            LogUtil.i("The app open ad is already showing.")
            return
        }
        if (!isAdAvailable(loadTime)) {
            LogUtil.i("The app open ad is not ready yet.")
//            loadAd(activity)
//                onShowAdCompleteListener.onShowAdComplete()
            return
        }
        LogUtil.i("Will show ad.")
        appOpenAd?.fullScreenContentCallback = object : FullScreenContentCallback() {
            override fun onAdDismissedFullScreenContent() {
                appOpenAd = null
                isShowingAd = false
                LogUtil.i("onAdDismissedFullScreenContent.")
                onShowAdCompleteListener.onShowAdComplete()
                loadAd(activity)
            }

            override fun onAdFailedToShowFullScreenContent(adError: AdError) {
                appOpenAd = null
                isShowingAd = false
                LogUtil.i("开屏广告 onAdFailedToShowFullScreenContent: " + adError.message)
//                onShowAdCompleteListener.onShowAdComplete()
                onShowAdCompleteListener.onAdFailedToShowFullScreenContent()
                loadAd(activity)
            }

            override fun onAdShowedFullScreenContent() {
                AdsCount.incrementDisplayCount()
                onShowAdCompleteListener.onAdShowedFullScreenContent()
                LogUtil.i("开屏广告 onAdShowedFullScreenContent.")
            }

            override fun onAdClicked() {
                AdsCount.incrementClickCount()
            }
        }
        isShowingAd = true
        appOpenAd?.show(activity)
    }

    fun releaseOpenAd() {
        if (appOpenAd != null) {
            appOpenAd = null
        }
        adListener = null
    }

    override fun clearCache() {
        LogUtil.i("观察者模式释放 开屏广告资源")
        if (appOpenAd != null) {
            appOpenAd = null
        }
        BpApplication.adMobOpenAdManager?.loadAd(BpApplication.context)
    }
}